<?php
/**
 * shop.inc.php
 */

if(!defined('IN_SITE') || !defined('IN_ADMIN')) {
	exit('Access Denied');
}

$op = $op ? $op : 'list';

switch ($op)
{
	/**
	 * 添加店铺
	 */
	case 'add':
		$areaselect = areaselect();
		$categoryradio = categoryradio();
	break;
	
	/**
	 * 保存店铺数据
	 */
	case 'saveadd':
		
		if ($dosubmit == '') showMessage('非法操作');
		if (empty($_FILES)) showMessage('请上传图片。');
		//$insertattasql = '';
		
		//上传展示图
		if($_FILES['showimg']['tmp_name']) //展示图
		{	
			require_once SITE_ROOT.'/include/upload.class.php';
			require_once SITE_ROOT.'/include/image.class.php';
			$dir = date('y').'/'.date('m');
			$savePath = SITE_ROOT."attachments/".$dir;
			
			$f = new upload("showimg", $savePath);
			$f->up();
			$img = $f->uploadedfiles;
			$showimg = $img[0]['filepath'];
//			$i = new image();
//			$i->thumb(SITE_ROOT."attachments/".$showimg_b,'',100,70,'_small');
//			$i->watermark(SITE_ROOT."attachments/".$showimg_b);
//			$showimg_b_name = explode(".", $showimg_b);
//			$showimg_s = $showimg_b_name[0].'_small.'.$showimg_b_name[1];
		}

		$zone = $zonechild == '' ? $zone : $zonechild;
		
		$areaname = $db->result_first("SELECT aname FROM `{$tablepre}area` WHERE aid = '$area'");
		$zonename = $db->result_first("SELECT zname FROM `{$tablepre}zone` WHERE zid = '$zone'");
		
		$query = $db->query("INSERT INTO `{$tablepre}shops` (sgrade, cid, uid, username, shopname, areaid, areaname, zoneid, zonename, location, announcement, mainitem, summary, bus, yytime, qq, tel, contact, map, showimg_s, showimg_m, showimg_b, cpp, isaudit, iscard, addsdtime) 
					VALUES ('$sgrade', '$cid', '$uuid', '$uname', '$shopname', '$area', '$areaname', '$zone', '$zonename', '$location', '$announcement', '$mainitem', '$summary', '$bus', '$yytime', '$qq', '$tel', '$contact', '$map', '', '', '$showimg', '$cpp', '1', '$iscard', '$timestamp')");
		$insertid = $db->insert_id();
		$sno = sprintf("%05d",$insertid);
		$db->query("UPDATE `{$tablepre}shops` SET sno = '$sno' WHERE sid = '$insertid'");
		
//		if (count($_FILES['attachments']['name']) > 1){ //上传附件并入库
//			$attachmentsinfo = uploadImage('attachments', '', '', 1028, 'resetfilename');
//			
//			for ($index = 0; $index < $attachmentsinfo['infocount']; $index++){
//				$attaurl = $attachmentsinfo[$index]['dir'].$attachmentsinfo[$index]['getfilename'];
//				list($width, $height) = getimagesize(HOLIDAY_ROOT.'attachments'.$attaurl);
//				if ($width >= 300 && $height >= 250){
//					water_IM($attachmentsinfo[$index]['type'][$index], HOLIDAY_ROOT.'attachments'.$attaurl);
//				}
//				$description = $attachmentsinfo[$index]['description'];
//				$insertattasql .= " ('$insertid', '$width', '$height', '$timestamp', '$description', '$attaurl'),";
//			}
//			
//			$insertattasql = substr($insertattasql, 0, strlen($insertattasql)-1);
//			$db->query("INSERT INTO `{$tablepre}attachments` (sid, width, height, dateline, description, attachment) VALUES $insertattasql");
//		}
		
		if($subcat != ''){
			foreach ($subcat as $val){
				$exp = explode('|', $val);
				$db->query("INSERT INTO `{$tablepre}shopsubcate` (subcateid, subcate, sid) VALUES ('$exp[0]', '$exp[1]', $insertid)");
				$count = $db->result_first("SELECT count(*) FROM `{$tablepre}subcate` WHERE subcateid = '$exp[0]' AND subcate = '$exp[1]'");
				if ($count){
					$db->query("UPDATE `{$tablepre}subcate` SET usecount = usecount+1 WHERE subcateid = '$exp[0]' AND subcate = '$exp[1]'");
				} else {
					$db->query("INSERT INTO `{$tablepre}subcate` (subcateid, subcate, usecount) VALUES ('$exp[0]', '$exp[1]', '1')");
				}
			}
		}
		//更新统计缓存
		statshops();
		shophy();
		$h = load("html.class.php");
		$h->shop($insertid);
		r_newshop();
		r_hotshop();
		tongji(1);
		showMessage('添加店铺成功。', '?action=shop&op=list');
		
	break;
	
	case 'getcidsub':
		if ($cid == '') return false;
		
		$query = $db->query("SELECT cid, cname FROM `{$tablepre}category` WHERE fid = '$cid'");
		while ($row = $db->fetch_array($query)) {
			$subcat[] = $row;
		}
		$count = count($subcat);
		
		if($shopid != '') {
			$query = $db->query("SELECT subcateid FROM `{$tablepre}shopsubcate` WHERE sid = '$shopid'");
			while ($row = $db->fetch_array($query)) {
				$checked[] = $row;
			}
			
			foreach ($checked as $val){
				$checkeds[] = $val['subcateid'];
			}
			
			for($i = 0; $i < $count; $i++){
				$checked = @in_array($subcat[$i]['cid'], $checkeds) ? 'checked' : '';
				$s .= "<input type='checkbox' name='subcat[]' value='".$subcat[$i]['cid']."|".$subcat[$i]['cname']."'";
				if($i == 0) { $s .= "dataType='Group' msg='子分类还没选呢'";}
				$s .= " $checked />".$subcat[$i]['cname'].'&nbsp;';
			}
			
		} else {
			for($i = 0; $i < $count; $i++){
				$s .= "<input type='checkbox' name='subcat[]' value='".$subcat[$i]['cid']."|".$subcat[$i]['cname']."'";
				if($i == 0) { $s .= "dataType='Group' msg='子分类还没选呢'";}
				$s .= " />".$subcat[$i]['cname'].'&nbsp;';
			}
		}
		
		header("Content-type: text/html; charset=GBK");
		exit($s);
	
	break;
	
	/**
	 * Ajax 方式返回商圈
	 */
	case 'getzone':
		if ($area == '') return false;
		
		$query = $db->query("SELECT zid, zname FROM `{$tablepre}zone` WHERE fid = '0' AND aid = '$area' ORDER BY displayorder ASC");
		while ($row = $db->fetch_array($query, MYSQL_NUM)) {
			$zonelist[] = $row;
		}
		$zoneselect = selectradio('', '', $zonelist, ($zone == '') ? '' : $zone, 'option');
		
		header("Content-type: text/html; charset=GBK");
		exit($zoneselect);
		
	break;
	
	/**
	 * Ajax方式返回商圈子分类
	 */
	case 'getzonechild':
		if ($zone == '') return false;
		
		$query = $db->query("SELECT zid, zname FROM `{$tablepre}zone` WHERE fid = '$zone' ORDER BY displayorder ASC");
		while ($row = $db->fetch_array($query, MYSQL_NUM)) {
			$zonechildlist[] = $row;
		}
		$zonechildlist = selectradio('', '', $zonechildlist, ($checked == '') ? '' : $checked, 'option');
		
		header("Content-type: text/html; charset=GBK");
		exit($zonechildlist);
		
	break;
	
	/**
	 * Ajax方式检查自定义编号
	 */
	case 'checkso':
		if ($number == '') return false;
		
		$sno = $db->result_first("SELECT sno FROM `{$tablepre}shops` WHERE sno = '$number'");
		exit($sno);
		
	break;
	
	case 'list':
		
		if ($shopname != '') $like = ' WHERE shopname like  \'%'.$shopname.'%\' ';
		$tpp = 50;
		$page = max(1, intval($page));
		$start = ($page - 1) * $tpp;
		
		$count = $db->result_first("SELECT count(*) FROM `{$tablepre}shops` $like");
		
		$shops = $db->fetch_all("SELECT sid, uid, username, shopname, sgrade, cid, location, score, recoms, isaudit FROM `{$tablepre}shops` $like ORDER BY sid DESC LIMIT $start, $tpp");
		$pageurl = $shopname != '' ? "admincp.php?action=shop&op=list&shopname=".urlencode($shopname) : 'admincp.php?action=shop&op=list';
		$multipage = multi($count, $tpp, $page, $pageurl);
		
	break;
	
	case 'edit':
		if ($sid == '') showMessage('店铺ID不能为空');
		
		$query = $db->query("SELECT sid, sno, sgrade, cid, uid, username, shopname, areaid, areaname, zoneid, zonename, location, announcement, mainitem, summary, bus, 
			yytime, qq, tel, contact, map, showimg_b, showimg_s, showimg_m, cpp, isaudit, iscard FROM `{$tablepre}shops` WHERE sid = '$sid'");
		$shop = $db->fetch_array($query);
		$categoryradio = categoryradio($shop['cid']);
		$areaselect = areaselect($shop['areaid']);
		$zoneparentid = getchildparent($shop['zoneid']);
		$query = $db->query("SELECT aid, sid, width, height, dateline, description, attachment as name FROM `{$tablepre}attachments` WHERE sid = '$sid'");
		while ($row = $db->fetch_array($query)) {
			$attachments[] = $row;
		}
	
	break;
	
	case 'saveedit':
		if ($dosubmit == '') showMessage('操作失败。');
		$whereimg = '';
			
		//上传展示图
		if($_FILES['showimg']['tmp_name']) //展示图
		{	
			require_once SITE_ROOT.'/include/upload.class.php';
			require_once SITE_ROOT.'/include/image.class.php';
			$dir = date('y').'/'.date('m');
			$savePath = SITE_ROOT."attachments/".$dir;
			
			$f = new upload("showimg", $savePath);
			$f->up();
			$img = $f->uploadedfiles;
			$showimg = $img[0]['filepath'];
//			$i = new image();
//			$i->thumb(SITE_ROOT."attachments/".$showimg_b,'',100,70,'_small');
//			$i->watermark(SITE_ROOT."attachments/".$showimg_b);
//			$showimg_b_name = explode(".", $showimg_b);
//			$showimg_s = $showimg_b_name[0].'_small.'.$showimg_b_name[1];
			$whereimg = "showimg_b='$showimg',";
		}

		$zone = $zonechild == '' ? $zone : $zonechild;
		$areaname = $db->result_first("SELECT aname FROM `{$tablepre}area` WHERE aid = '$area'");
		$zonename = $db->result_first("SELECT zname FROM `{$tablepre}zone` WHERE zid = '$zone'");
		$sno = sprintf("%05d",$sno);

		$query = $db->query("UPDATE `{$tablepre}shops` SET sgrade='$sgrade', sno='$sno', cid='$cid', uid='$uuid', username='$uname', shopname='$shopname', 
			areaid='$area', areaname='$areaname', zoneid='$zone', zonename='$zonename', location='$location', announcement='$announcement', mainitem='$mainitem', 
			summary='$summary', bus='$bus', yytime='$yytime', qq='$qq', tel='$tel', contact='$contact', map='$map', $whereimg cpp='$cpp', isaudit='$isaudit', iscard='$iscard' WHERE sid = '$sid'");
	
//		if (count($_FILES['attachments']['name']) > 1){ //上传附件并入库
//			$attachmentsinfo = uploadImage('attachments', '', '', 1028, 'resetfilename');
//			
//			for ($index = 0; $index < $attachmentsinfo['infocount']; $index++){
//				$attaurl = $attachmentsinfo[$index]['dir'].$attachmentsinfo[$index]['getfilename'];
//				list($width, $height) = getimagesize(HOLIDAY_ROOT.'attachments'.$attaurl);
//				if ($width >= 300 && $height >= 250){
//					water_IM($attachmentsinfo[$index]['type'][$index], HOLIDAY_ROOT.'attachments'.$attaurl);
//				}
//				$description = $attachmentsinfo[$index]['description'];
//				$insertattasql .= " ('$sid', '$width', '$height', '$timestamp', '$description', '$attaurl'),";
//			}
//
//			$insertattasql = substr($insertattasql, 0, strlen($insertattasql)-1);
//			$db->query("INSERT INTO `{$tablepre}attachments` (sid, width, height, dateline, description, attachment) VALUES $insertattasql");
//		}
		
		if($subcat != '')
		{
			$query = $db->query("SELECT subcateid FROM `{$tablepre}shopsubcate` WHERE sid = '$sid'");
			while ($row = $db->fetch_array($query)){
				$subcateid .= $row['subcateid'].',';
			}
			$db->query("DELETE FROM `{$tablepre}shopsubcate` WHERE sid = '$sid'");
			$subcateid = substr($subcateid, 0, strlen($subcateid)-1);
			if ($subcateid){
				@$db->query("UPDATE `{$tablepre}subcate` SET usecount=usecount-1 WHERE subcateid IN ($subcateid)");
			}
			
			foreach ($subcat as $val)
			{
				$exp = explode('|', $val);
				$db->query("INSERT INTO `{$tablepre}shopsubcate` (subcateid, subcate, sid) VALUES ('$exp[0]', '$exp[1]', '$sid')");
				$count = $db->result_first("SELECT count(*) FROM `{$tablepre}subcate` WHERE subcateid = '$exp[0]' AND subcate = '$exp[1]'");
				if ($count){
					$db->query("UPDATE `{$tablepre}subcate` SET usecount = usecount+1 WHERE subcateid = '$exp[0]' AND subcate = '$exp[1]'");
				} else {
					$db->query("INSERT INTO `{$tablepre}subcate` (subcateid, subcate, usecount) VALUES ('$exp[0]', '$exp[1]', '1')");
				}
			}
		} else {
			$query = $db->query("SELECT subcateid FROM `{$tablepre}shopsubcate` WHERE sid = '$sid'");
			while ($row = $db->fetch_array($query)){
				$subcateid .= $row['subcateid'].',';
			}
			
			$subcateid = substr($subcateid, 0, strlen($subcateid)-1);
			if ($subcateid){
				@$db->query("DELETE FROM `{$tablepre}shopsubcate` WHERE sid = '$sid'");
				@$db->query("UPDATE `{$tablepre}subcate` SET usecount=usecount-1 WHERE subcateid IN ($subcateid)");
			}
		}
		
		//更新店铺统计
		statshops();
		$h = load("html.class.php");
		$h->shop($sid);
		//关闭店铺
		if($isaudit != 1) {@unlink(SITE_ROOT.'shop/'.$sid.'.shtml');}
		r_newshop();
		r_hotshop();
		//工作统计
		tongji(2);
		showMessage('修改店铺成功。', $referer ? urldecode($referer) : '?action=shop&op=list');
		
	break;
	
	case 'delete':
		if (is_array($sid)){
			$sid = implode(',', $sid);
			
			$shops = $db->fetch_all("SELECT sid, showimg_s, showimg_m, showimg_b FROM `{$tablepre}shops` WHERE sid IN ($sid)");
			
			foreach ($shops as $val){
				@unlink(SITE_ROOT.'attachments'.$val['showimg_s']);
				@unlink(SITE_ROOT.'attachments'.$val['showimg_m']);
				@unlink(SITE_ROOT.'attachments'.$val['showimg_b']);
				
				//$db->query("DELETE FROM `{$tablepre}shopupgrade` WHERE sid = '{$val['sid']}'");
				@unlink(SITE_ROOT.'shop/'.$val['sid'].'.shtml');
			}
			$query = $db->query("DELETE FROM `{$tablepre}shops` WHERE sid IN ($sid)");
			
			$atta = $db->fetch_all("SELECT attachment FROM `{$tablepre}attachments` WHERE sid IN ($sid)");
			
			foreach ($atta as $val){
				@unlink(SITE_ROOT.'attachments'.$val['attachment']);
			}
			
			$db->query("DELETE FROM `{$tablepre}attachments` WHERE sid IN ($sid)");
			
			//更新统计缓存
			statshops();
			r_newshop();
			r_hotshop();
			showMessage('删除店铺成功。', $referer ? urldecode($referer) : '?action=shop&op=list');
		}
//		else {
//			if ($sid == '') showMessage('操作错误。');
//			$query = $db->query("SELECT showimg_s, showimg_m, showimg_b FROM `{$tablepre}shops` WHERE sid = '$sid'");
//			$shops = $db->fetch_array($query);
//			@unlink(HOLIDAY_ROOT.'attachments'.$shops['showimg_s']);
//			@unlink(HOLIDAY_ROOT.'attachments'.$shops['showimg_m']);
//			@unlink(HOLIDAY_ROOT.'attachments'.$shops['showimg_b']);
//			$query = $db->query("DELETE FROM `{$tablepre}shops` WHERE sid = '$sid'");
//			
//			$url = $db->result_first("SELECT attachment FROM `{$tablepre}attachments` WHERE sid IN ($sid)");
//			@unlink(HOLIDAY_ROOT.'attachments'.$url);
//			$db->query("DELETE FROM `{$tablepre}attachments` WHERE sid = '$sid'");
//		}

	break;
	
	/**
	 * Ajax方式删除附件
	 */
	case 'delatta':
		if ($aid == '' || $shopid == '') return false;
		
		$url = $db->result_first("SELECT attachment FROM `{$tablepre}attachments` WHERE aid = '$aid'");
		@unlink(SITE_ROOT.'attachments'.$url);

		$query = $db->query("DELETE FROM `{$tablepre}attachments` WHERE aid = '$aid'");
		exit($query);
	
	break;
	
	/**
	 * Ajax方式更新发件描述
	 */
	case 'updatedes':
		if ($aid == '' || $value == '') return false;
		
		$value=iconv("UTF-8","GBK",$value);
		$query = $db->query("UPDATE `{$tablepre}attachments` SET description = '$value' WHERE aid = '$aid'");
		exit($query);
	
	break;
}

include admin_tpl("shop");

function categoryradio($checked = ''){
	global $db, $tablepre;
	//店铺分类
	
	$query = $db->query("SELECT cid, cname FROM `{$tablepre}category` WHERE fid = '0'");
	while ($row = $db->fetch_array($query, MYSQL_NUM)) {
		$categorylist[] = $row;
	}
	$categoryradio = selectradio('', 'cid', $categorylist, $checked, 'radio', ' onclick="getcatsub();"', "dataType='Group' msg='分类必选'");
	
	return $categoryradio;
}

function areaselect($selected = ''){
	global $db, $tablepre;
	
	//所有地区
	$query = $db->query("SELECT aid, aname FROM `{$tablepre}area` ORDER BY displayorder ASC");
	while ($row = $db->fetch_array($query, MYSQL_NUM)) {
		$arealist[] = $row;
	}
	$areaselect = selectradio('area', 'area', $arealist, $selected, 'select', 'dataType=\"Require\" msg=\"请选择地区\"');
	
	return $areaselect;
}

function getchildparent($zoneid){
	global $db, $tablepre;
	
	$query = $db->query("SELECT zid, fid FROM `{$tablepre}zone` WHERE zid='$zoneid'");
	$zone = $db->fetch_array($query);
	
	return $zone['fid'] ? getchildparent($zone['fid']) : $zone['zid'];	
}
?>